#include "TcpServer.hpp"
#include <memory>
#include "Protocol.hpp"

using namespace ns_tcpserver;
using namespace ns_protocol;

static void Usage(const std::string& proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl;
}

static Response calculatorHelper(const Request& req)
{
    Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (0 == req._y)
        {
            resp._code = 1;
        }
        else
        {
            resp._result = req._x / req._y;
        }
        break;
    case '%':
        if (0 == req._y)
        {
            resp._code = 2;
        }
        else
        {
            resp._result = req._x % req._y;
        }
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void calculator(int sock)
{
    while (true)
    {
        std::string str = Recv(sock);//在这里读到了一个请求
        Request req;
        req.Deserialized(str);//反序列化
        Response resp = calculatorHelper(req);

        std::string respString = resp.Serialize();//对计算结果进行序列化
        Send(sock, respString);
    }
}

// ./CalServer port
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindService(calculator);
    server->Start();

    // Request req(123, 456, '+');
    // std::string s = req.Serialize();
    // std::cout << s << std::endl;

    // Request temp;
    // temp.Deserialized(s);
    // std::cout << temp._x << std::endl;
    // std::cout << temp._op << std::endl;
    // std::cout << temp._y << std::endl;

    return 0;
}